<template>
  <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
    <el-row>
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-form-item :label="`${formData.tenantTypeName}类型`" prop="tenantType">
          <el-select
            v-model="formData.tenantType"
            :placeholder="`请选择${formData.tenantTypeName}类型`"
            @change="tenantTypeChange"
            clearable
            :disabled="formData.id != undefined"
          >
            <el-option
              v-for="dict in listTenantType"
              :key="dict.code"
              :label="dict.label"
              :value="dict.code"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-form-item :label="`${formData.tenantTypeName}套餐`" prop="packageId">
          <el-select
            v-model="formData.packageId"
            :disabled="!formData.tenantType"
            clearable
            :placeholder="`请选择${formData.tenantTypeName}套餐`"
          >
            <el-option
              v-for="item in tenantPackageList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-form-item :label="`同步开通`">
          <el-checkbox-group v-model="formData.openType">
            <el-checkbox label="门店" :value="4" />
            <el-checkbox label="商城" :value="5" />
          </el-checkbox-group>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row v-if="formData.packageId && tenantPackageList?.length > 0">
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-form-item>
          <el-table
            :data="[
              tenantPackageList.find((item) => {
                return item.id == formData.packageId
              })
            ]"
          >
            <el-table-column align="center" label="套餐" min-width="80">
              <template #default="{ row }">
                {{ row.name }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="套餐类型" min-width="80">
              <template #default="{ row }">
                <dict-tag :type="DICT_TYPE.TENANT_IDENTITY" :value="row.type" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="数量" min-width="80">
              <template #default="{ row }">
                <el-input-number v-model="row.tenantNum" :controls="false" disabled />
              </template>
            </el-table-column>
            <!-- <el-table-column align="center" label="操作" min-width="80">
              <template #default>
                <el-link type="primary">修改 </el-link>
                <el-link type="primary" class="ml-10px">删除 </el-link>
              </template>
            </el-table-column> -->
          </el-table>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-form-item :label="`${formData.tenantTypeName}名称`" prop="name">
          <el-input v-model="formData.name" :placeholder="`请输入${formData.tenantTypeName}名称`" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-form-item v-if="formData.id === undefined" label="管理员姓名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入管理员姓名" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-form-item label="手机(账号)" prop="contactMobile">
          <el-input v-model="formData.contactMobile" placeholder="请输入用户名称" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-form-item :label="`授权套餐`" prop="affiliatePackageId">
          <el-select
            v-model="formData.affiliatePackageId"
            multiple
            clearable
            :placeholder="`请选择授权套餐`"
            @change="packageIdsChange"
          >
            <el-option
              v-for="item in tenantPackageList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              {{ item.name }}
              <dict-tag :type="DICT_TYPE.TENANT_IDENTITY" :value="item.type" />

              <!-- 来源 套餐数量 剩余套餐数量 -->
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row v-if="formData.packageIdsList && formData.packageIdsList.length > 0">
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-form-item>
          <el-table :data="formData.packageIdsList">
            <el-table-column align="center" label="套餐" min-width="80">
              <template #default="{ row }">
                {{ row.name }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="套餐类型" min-width="80">
              <template #default="{ row }">
                <dict-tag :type="DICT_TYPE.TENANT_IDENTITY" :value="row.type" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="数量" min-width="80">
              <template #default="{ row }">
                <el-input-number v-model="row.tenantNum" :controls="false" disabled />
              </template>
            </el-table-column>
            <!-- <el-table-column align="center" label="操作" min-width="80">
              <template #default>
                <el-link type="primary">修改 </el-link>
                <el-link type="primary" class="ml-10px">删除 </el-link>
              </template>
            </el-table-column> -->
          </el-table>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-form-item :label="`授权岗位`" prop="postIds">
          <el-select v-model="formData.postIds" multiple clearable :placeholder="`请选择授权岗位`">
            <el-option
              v-for="item in postOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              {{ item.name }}
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-form-item label="有效日期" prop="tenantIndate">
          <el-input v-model="formData.tenantIndate" clearable placeholder="请输入有效日期">
            <template #append>
              <el-form-item prop="tenantIndate">
                <el-select v-model="formData.tenantIndateUnit" class="w-60px!">
                  <el-option
                    v-for="dict in getIntDictOptions(DICT_TYPE.TENANT_DATE_UNIT)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="2" v-if="formData.id !== undefined">
        <el-button
          link
          type="primary"
          @click="validityTimeChangeFormRef?.open(formData.tenantIndateUnit)"
        >
          <Icon icon="ep:edit" :size="24" />
        </el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-form-item label="过期时间" prop="expireTime">
          <el-date-picker
            v-model="formData.expireTime"
            clearable
            placeholder="请选择过期时间"
            type="date"
            value-format="x"
            class="!w-100%"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-form-item label="微信AppId" prop="wxAppid">
          <el-input v-model="formData.wxAppid" placeholder="请输入微信小程序AppId" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-form-item label="绑定域名" prop="website">
          <el-input v-model="formData.website" placeholder="请输入绑定域名" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-form-item :label="`${formData.tenantTypeName}状态`" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio
              v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
              :key="dict.value"
              :value="dict.value"
            >
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-form-item label="会员共享商户">
          <el-select
            v-model="formData.shareTenants"
            clearable
            multiple
            collapse-tags
            :max-collapse-tags="4"
          >
            <el-option
              v-for="item in storeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-form-item label="允许共享会员">
          <el-switch v-model="formData.enableShareUser" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-form-item label="接受共享会员">
          <el-switch v-model="formData.enableAcceptUser" />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <ValidityTimeChangeForm ref="validityTimeChangeFormRef" />
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { propTypes } from '@/utils/propTypes'
import type { TenantVO } from '@/api/system/tenant'
import { CommonStatusEnum } from '@/utils/constants'
import * as TenantPackageApi from '@/api/system/tenantPackage'
import * as PostApi from '@/api/system/post'

import { copyValueToTarget } from '@/utils'
import ValidityTimeChangeForm from './ValidityTimeChangeForm.vue'
import { handleTree } from '@pureadmin/utils'
defineOptions({ name: 'SystemTenantForm' })

const props = defineProps({
  propFormData: {
    type: Object as PropType<TenantVO>,
    default: () => {}
  },
  activeName: propTypes.string.def('tenant')
})

const message = useMessage() // 消息弹窗

const formData = reactive<TenantVO>({
  id: undefined,
  name: undefined,
  packageId: undefined,
  contactMobile: undefined,
  accountCount: undefined,
  expireTime: undefined,
  website: undefined,
  wxAppid: undefined,
  status: CommonStatusEnum.ENABLE,
  tenantType: undefined,
  tenantTypeName: '商户',
  tenantIndate: undefined,
  tenantIndateUnit: 0,
  enableAcceptUser: false,
  enableShareUser: false,
  shareTenants: [],
  affiliatePackageId: [],
  packageIdsList: [],
  postIds: [],
  openType: []
})
const formRules = reactive({
  tenantType: [required],
  name: [required],
  packageId: [required],
  // contactMobile: [required],
  status: [required],
  accountCount: [required],
  // expireTime: [required],
  // website: [required],
  username: [required],
  // affiliatePackageId: [required],
  tenantIndate: [
    // required,
    {
      pattern: /^[1-9]\d*$/,
      message: '请输入正整数',
      trigger: 'blur'
    }
  ]
})
const formRef = ref() // 表单 Ref

const validityTimeChangeFormRef = ref() //有效期修改 Ref
/** 表单校验 */
const emit = defineEmits(['update:activeName'])
const validate = async () => {
  if (!formRef) return
  try {
    await unref(formRef)?.validate()
    // 校验通过更新数据
    Object.assign(props.propFormData, formData)
  } catch (e) {
    message.error('【基础信息】不完善，请填写相关信息')
    emit('update:activeName', 'tenant')
    throw e // 目的截断之后的校验
  }
}
defineExpose({ validate })
/** 租户类型改变时 */
const tenantPackageList = ref()
const tenantTypeChange = async () => {
  formData.packageId = undefined
  getTenantType()
}
const getTenantType = async () => {
  if (formData.tenantType) {
    Object.assign(props.propFormData, formData)
    // 获取当前选择的类型的套餐

    tenantPackageList.value = await TenantPackageApi.getTenantPackageList()
  } else {
    tenantPackageList.value = []
  }
}
/** 关联套餐改变时 */
const packageIdsChange = () => {
  let selectPackageIds = formData.affiliatePackageId

  if (selectPackageIds && selectPackageIds.length > 0) {
    formData.packageIdsList = tenantPackageList.value
      .filter((ele) => {
        return selectPackageIds.includes(ele.id)
      })
      .map((ele) => {
        return { ...ele, number: undefined }
      })
  } else {
    formData.packageIdsList = []
  }
}

/** 将传进来的值赋值给 formData */
watch(
  () => props.propFormData,
  (data) => {
    if (!data) {
      return
    }
    copyValueToTarget(formData, data)
  },
  {
    immediate: true
  }
)
const listTenantType = ref()
import * as TenantApi from '@/api/system/tenant'
import { getTenantTypeValue } from '@/utils/auth'
const storeList = ref<any[]>([]) // 门店列表
const postOptions = ref<PostApi.PostVO[]>([]) // 岗位列表

// 加载套餐列表
onMounted(async () => {
  // 根据租户类型查询级联租户类型
  const tenantTypeValue = getTenantTypeValue()
  listTenantType.value = handleTree(
    await TenantApi.getListTenantType({ type: tenantTypeValue.toString(), flag: 0 })
  )
  // 获取门店列表
  const storeData = await TenantApi.getTenantPage({ tenantType: 4 })
  storeList.value = storeData.list
  // 获得岗位列表
  postOptions.value = await PostApi.getSimplePostList()
  if (formData.id) {
    // 如果有id 说明是修改
    getTenantType()
  }
})
</script>
<style lang="scss">
.el-input-number .el-input__inner {
  text-align: left;
}
</style>
